/*
 * @copyright Copyright (c) 2010 Laboratório de Educação Cerebral. (http://www.educacaocerebral.com.br)
 *
 * This file is part of SoftVFC.
 *
 * SoftVFC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SoftVFC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SoftVFC.  If not, see <http://www.gnu.org/licenses/>.
 *
 * *********************
 *
 * Este arquivo é parte do programa SoftVFC.
 *
 * SoftVFC é um software livre; você pode redistribui-lo e/ou
 * modifica-lo dentro dos termos da Licença Pública Geral GNU como
 * publicada pela Fundação do Software Livre (FSF); na versão 3 da
 * Licença.
 *
 * Este programa é distribuido na esperança que possa ser util,
 * mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer
 * MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a
 * Licença Pública Geral GNU para maiores detalhes.
 *
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU
 * junto com este programa, se não, acesse no website oficial:
 * http://www.gnu.org/licenses/gpl.html
 *
 */
package org.softvfc.tablehandler.file;

import java.awt.Point;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.Vector;
import java.util.regex.Pattern;
import javax.swing.JProgressBar;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import org.openide.util.Exceptions;

/**
 *
 * @author Diego Schmaedech Martins (schmaedech@gmail.com)
 * @version 29/07/2010
 */
public class TableImporter {

    private String regex = "";
    private Vector<String> fileRows = new Vector<String>(); 
    private int rowCount = 0;
    private int columnCount = 0;
    private boolean firstRowAsColumn = false;
    private int firstRow = 0;
    private TableModel tableModel = null;

    public TableImporter(){

    }

    public void update(JProgressBar progressBar){

        TableModel model = null;
        Pattern col = Pattern.compile(getRegex());
        String[] headers = col.split(fileRows.elementAt(getFirstRow()));
        setColumnCount(headers.length);
        progressBar.setMinimum(0);
        
        if(isFirstRowAsColumn()){
            model = new ImporterTableModel(fileRows.size()-getFirstRow()-1, headers);
            progressBar.setMaximum(fileRows.size()-getFirstRow()-1);

            for (int i = getFirstRow()+1; i < fileRows.size(); i++) {
                Pattern row = Pattern.compile(getRegex());
                String[] srows = row.split(fileRows.elementAt(i));
                for (int j = 0; j < srows.length; j++) {
                     model.setValueAt(srows[j], i-getFirstRow()-1, j);
                     progressBar.setValue(i);
                }

            }
            
        }else{
            for (int i = 0; i < headers.length; i++) {
                headers[i] = "Column "+i;
            }
            model = new ImporterTableModel(fileRows.size()-getFirstRow(), headers);
            progressBar.setMaximum(fileRows.size()-getFirstRow());

            for (int i = getFirstRow(); i < fileRows.size(); i++) {
                Pattern row = Pattern.compile(getRegex());
                String[] srows = row.split(fileRows.elementAt(i));
                for (int j = 0; j < srows.length; j++) {
                     model.setValueAt(srows[j], i-getFirstRow(), j);
                     progressBar.setValue(i+1);
                }
            }
        }


        setTableModel(model);

    }

    public void importTable(File file){

        try {
            Scanner scanner = new Scanner(file);
            scanner.useDelimiter(System.getProperty("line.separator"));
            while (scanner.hasNext()) {
                fileRows.add(scanner.next());
            }
            setRowCount(fileRows.size());
            scanner.close();

        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }

    }

    /**
     * @return the rowCount
     */
    public int getRowCount() {
        return rowCount;
    }

    /**
     * @param rowCount the rowCount to set
     */
    public void setRowCount(int rowCount) {
        this.rowCount = rowCount;
    }

    /**
     * @return the regex
     */
    public String getRegex() {
        return regex;
    }

    /**
     * @param regex the regex to set
     */
    public void setRegex(String regex) {
        this.regex = regex;
    }

    /**
     * @return the columnCount
     */
    public int getColumnCount() {
        return columnCount;
    }

    /**
     * @param columnCount the columnCount to set
     */
    public void setColumnCount(int columnCount) {
        this.columnCount = columnCount;
    }

    /**
     * @return the firstRowAsColumn
     */
    public boolean isFirstRowAsColumn() {
        return firstRowAsColumn;
    }

    /**
     * @param firstRowAsColumn the firstRowAsColumn to set
     */
    public void setFirstRowAsColumn(boolean firstRowAsColumn) {
        this.firstRowAsColumn = firstRowAsColumn;
    }

    /**
     * @return the firstRow
     */
    public int getFirstRow() {
        return firstRow;
    }

    /**
     * @param firstRow the firstRow to set
     */
    public void setFirstRow(int firstRow) {
        this.firstRow = firstRow;
    }

    /**
     * @return the tableModel
     */
    public TableModel getTableModel() {
        return tableModel;
    }

    /**
     * @param tableModel the tableModel to set
     */
    public void setTableModel(TableModel tableModel) {
        this.tableModel = tableModel;
    }

    class ImporterTableModel extends AbstractTableModel {

        private Hashtable<Point,Object> lookup;
        private final int rows;
        private final int columns;
        private final String headers[];
        public ImporterTableModel(int rows, String columnHeaders[]) {
            if ((rows < 0) || (columnHeaders == null)) {
              throw new IllegalArgumentException("Invalid row count/columnHeaders");
            }
            this.rows = rows;
            this.columns = columnHeaders.length;
            headers = columnHeaders;
            lookup = new Hashtable<Point,Object>();
        }

        @Override
        public int getColumnCount() {
        return columns;
        }

        @Override
        public int getRowCount() {
            return rows;
        }

        @Override
        public String getColumnName(int column) {
            return headers[column];
        }

        @Override
        public Object getValueAt(int row, int column) {
            return lookup.get(new Point(row, column));
        }

        @Override
        public void setValueAt(Object value, int row, int column) {
            if ((rows < 0) || (columns < 0)) {
                throw new IllegalArgumentException("Invalid row/column setting");
            }
            if ((row < rows) && (column < columns)) {
                Point point = new Point(row, column);
                lookup.put(point, value);
            }
            fireTableDataChanged();
        }
    }
}
